package com.whj.service.impl;

import com.whj.domain.dto.LoginUserDTO;
import com.whj.domain.entity.LoginUser;
import com.whj.domain.entity.User;
import com.whj.domain.response.ResponseResult;
import com.whj.domain.vo.BlogUserLoginVo;
import com.whj.domain.vo.UserInfoVo;
import com.whj.service.LoginService;
import com.whj.utils.BeanCopyUtils;
import com.whj.utils.JwtUtil;
import com.whj.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Objects;

import static org.springframework.security.core.context.SecurityContextHolder.*;

/**
 * @Auther: wanghaijun
 * @Date: 2023/5/23 - 05 - 23 - 15:01 
 * @Description: com.whj.com.whj.service.impl
 */

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    // 注入redis的工具类
    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(LoginUserDTO loginUserDTO) {

        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUserDTO.getUserName(), loginUserDTO.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //判断是否认证通过
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户名或密码错误");
        }
        //获取userid 生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        Long userId = loginUser.getUser().getId();
        String token = JwtUtil.createJWT(userId.toString());
        //把用户信息存入redis
        redisCache.setCacheObject("bloglogin:" + userId, loginUser);

        //把token和userinfo封装 返回
        BlogUserLoginVo blogUserLoginVo = new BlogUserLoginVo();
        blogUserLoginVo.setToken(token);
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(loginUser.getUser(), UserInfoVo.class);
        blogUserLoginVo.setUserInfo(userInfoVo);
        return ResponseResult.okResult(blogUserLoginVo);
    }

    /**
     * 退出登录  删除redis中的信息
     *
     * @return
     */
    @Override
    public ResponseResult logout() {
        //获取token 解析获取userId  因为进行登录安全验证的时候在JwtAuthenticationTokenFilter中保存了用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        //获取userId
        Long userId = loginUser.getUser().getId();
        redisCache.deleteObject("bloglogin:"+userId);
        return ResponseResult.okResult();
    }
}
